<template>
  <div class="content-detail">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header
          icon="el-icon-arrow-left"
          :content="title"
          @back="goback"
        >
        </el-page-header>
        <div v-if="isEdit" class="card-box--downloadbtn">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>模版基础信息</span>

          <div v-if="showInfo" @click="showInfo = !showInfo" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="showInfo = !showInfo" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <el-form
          :model="formData"
          class="content-box"
          :rules="rules"
          ref="formDataRef"
          label-width="160px"
          v-show="showInfo"
        >
          <template v-if="!templateId">
            <el-form-item label="模板名称" prop="projectTemplateName">
              <el-input
                v-model.trim="formData.projectTemplateName"
                class="width-custom200"
              ></el-input>
            </el-form-item>
            <el-form-item label="适用项目类型" prop="projectTmpTypeCode">
              <el-select
                v-model="formData.projectTmpTypeCode"
                v-if="isEdit"
                value-key="dicCode"
                class="width-custom200"
              >
                <el-option
                  class="default-option"
                  v-for="item in projectTypeList"
                  :label="item.dicValue"
                  :key="item.dicCode"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="模板描述">
              <el-input
                type="textarea"
                v-model.trim="formData.remarks"
                :rows="3"
              ></el-input>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="模板名称">
              <p class="text--info detail-text">
                {{ formData.projectTemplateName }}
              </p>
            </el-form-item>
            <el-form-item label="适用项目类型">
              <p class="text--info detail-text">
                {{ formData.projectTmpTypeName }}
              </p>
            </el-form-item>
            <el-form-item label="模板描述">
              <p class="text--info detail-text w100">{{ formData.remarks }}</p>
            </el-form-item>
          </template>
        </el-form>
      </el-collapse-transition>
    </el-card>
    <el-card class="card-box">
      <template #header>
        <div class="card-box-header">
          <span>项目模版配置</span>

          <div v-if="showSet" @click="showSet = !showSet" class="header-btn">
            <span>收起</span><i class="ml10 snowfont icon-shouqi"></i>
          </div>
          <div v-else @click="showSet = !showSet" class="header-btn">
            <span>展开</span><i class="ml10 snowfont icon-zhankai"></i>
          </div>
        </div>
      </template>
      <el-collapse-transition>
        <div v-show="showSet" class="content-box">
          <status-task-edit
            ref="editRef"
            :mode="isEdit ? 'edit' : 'read'"
            :templateId="templateId"
            :data="proStageList"
            :checkbox="false"
          ></status-task-edit>
        </div>
      </el-collapse-transition>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import NotifMessage from "/@/utils/message/notification";
import {
  getTemplateInfo,
  addTemplateList,
  updateTemplateList
} from "/@/api/projects";
import { postDictList } from "/@/api/home";
import StatusTaskEdit from "../../../components/template/index.vue";

export default defineComponent({
  components: { StatusTaskEdit },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const formDataRef = ref<HTMLFormElement | null>(null) as any;
    const editRef = ref<HTMLFormElement | null>(null) as any;
    let userList = ref([]);
    let projectTypeList = ref([]);

    let isEdit = route.query?.isEdit === "1";
    let templateId = route.query.id;
    let title = isEdit
      ? templateId
        ? "编辑项目模版"
        : "创建项目模版"
      : "查看项目模版";

    let state = reactive({
      formData: {
        projectTemplateName: "",
        projectTmpTypeCode: "" as any,
        projectTmpTypeName: "",
        remarks: ""
      },
      showInfo: true,
      showSet: true
    });

    let proStageList = ref([]);

    const rules = {
      projectTemplateName: [
        { required: true, message: "请填写模板名称", trigger: "blur" },
        { min: 3, max: 60, message: "长度在 3 到 60 个字符", trigger: "blur" }
      ],
      projectTmpTypeCode: [
        { required: true, message: "请选择适用项目类型", trigger: "change" }
      ]
    };
    // 项目类型
    const initProjectTypeList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_pro_type" });
        projectTypeList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };
    initProjectTypeList();

    const goback = () => {
      router.push("/projects/template/project");
    };

    // 请求页面数据
    const getData = async () => {
      if (!templateId) {
        return;
      }
      try {
        const { code, data } = await getTemplateInfo({ id: templateId });
        if (code === 200) {
          const {
            projectTemplateName,
            projectTmpTypeCode,
            projectTmpTypeName,
            remarks,
            proStageList: proStageListData
          } = data;
          state.formData = {
            projectTemplateName,
            projectTmpTypeCode,
            projectTmpTypeName,
            remarks
          };
          proStageList.value = [...proStageListData];
        }
      } catch (err) {
        console.log(err);
      }
    };

    templateId && getData();

    // 保存
    const handleSave = async () => {
      try {
        const isValid = await new Promise(resolve =>
          formDataRef.value.validate(resolve)
        );
        if (!isValid) return;

        editRef.value
          .save()
          .then(async data => {
            console.log(data);
            const params = {
              id: (templateId && Number(templateId)) || "",
              ...state.formData,
              projectTmpTypeName: templateId
                ? state.formData.projectTmpTypeName
                : state.formData.projectTmpTypeCode?.dicValue,
              projectTmpTypeCode: templateId
                ? state.formData.projectTmpTypeCode
                : state.formData.projectTmpTypeCode?.dicCode,
              proStageList: data
            };
            const { code, message } = await (templateId
              ? updateTemplateList(params)
              : addTemplateList(params));
            commonBackFn(code, message);
          })
          .catch(err => {
            console.log("error", err);
            NotifMessage.warning(err);
          });
      } catch (err) {
        console.log(err);
      }
    };

    const commonBackFn = (code: Number, message: String) => {
      if (code === 200) {
        NotifMessage.success(message);
        goback();
      } else {
        if (!message) return;
        NotifMessage.error(message);
      }
    };

    return {
      ...toRefs(state),
      isEdit,
      templateId,
      title,
      proStageList,

      formDataRef,
      editRef,
      userList,
      projectTypeList,
      rules,
      route,
      goback,
      handleSave
    };
  }
});
</script>

<style lang="scss" scoped></style>
